package com.example.travel.controller;



import com.example.travel.pojo.Category;
import com.example.travel.pojo.Route;
import com.example.travel.pojo.RouteImg;
import com.example.travel.pojo.Seller;
import com.example.travel.service.RouteService;
import com.github.pagehelper.PageInfo;
import org.apache.commons.io.FilenameUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.UUID;

@Controller
@RequestMapping("admin/route")
public class RouteController {

    @Autowired
    private RouteService routeService;

    //之后都基于返回admin/route/page
    //多条件分页查询
    @RequestMapping("page")
    public String allInfo(//查询条件
                          @RequestParam(defaultValue = "1") int pageNum,
                          @RequestParam(defaultValue = "10") int pageSize,
                          @RequestParam(value = "rname",defaultValue = "") String rName,
                          @RequestParam(value = "routeIntroduce",defaultValue = "") String routeIntroduce,
                          //int值需要默认值，否则为空将报错
                          @RequestParam(value = "cid",defaultValue = "0") Integer cid,
                          @RequestParam(value = "sid",defaultValue = "0") Integer sid,
                          Model model){

        Route route = new Route();
        if (rName !=null){
            route.setRName(rName.trim());
        }

        if (routeIntroduce !=null){
            route.setRouteIntroduce(routeIntroduce.trim());
        }

        if (cid != 0){
            route.setCid(cid);
        }

        if (sid !=0){
            route.setSid(sid);
        }

        //存储搜索条件
        model.addAttribute("condition",route);

        PageInfo<Route> routePageInfo = routeService.PageInfoFindByParam(pageNum, pageSize, route);
        //存分页信息
        model.addAttribute("page",routePageInfo);

        //下拉列表数据
        List<Category> categories = routeService.allCategory();

        model.addAttribute("categories",categories);

        List<Seller> sellers = routeService.allSeller();

        model.addAttribute("sellers",sellers);


        return "route/list";
    }

    //添加下拉列表数据到add页
    @RequestMapping("toAdd")
    public String goToAddPage(Model model){

        //下拉列表数据
        List<Category> categories = routeService.allCategory();

        model.addAttribute("categories",categories);

        List<Seller> sellers = routeService.allSeller();

        model.addAttribute("sellers",sellers);

        return "route/add";

    }

    //添加提交数据操作
    @PostMapping("add")
    public String add(Route route,
                      @RequestParam("rimageFile") MultipartFile rImageFile,
                      HttpServletRequest request) throws IOException {

        //项目部署目录+img/product/rImage/
        performRImage(route,rImageFile,request);

        int flag = routeService.addRoute(route);

        if (flag >=1 ){
            return "redirect:/admin/route/page";
        }else {
            return "error";
        }
    }

    //更新前回显数据
    @RequestMapping("getInfo/{rid}")
    public String getInfoToEdit(@PathVariable("rid") Integer rid,
                                Model model){

        Route info = routeService.getInfoById(rid);
        model.addAttribute("route",info);

        List<Category> categories = routeService.allCategory();

        model.addAttribute("categories",categories);

        List<Seller> sellers = routeService.allSeller();

        model.addAttribute("sellers",sellers);

        return "route/edit";

    }

    //更新数据
    @RequestMapping("doUpdate")
    public String doUpdate(Route route,
                           @RequestParam("rimageFile") MultipartFile rImageFile,
                           HttpServletRequest request) throws IOException {

        performRImage(route,rImageFile,request);

        int flag = routeService.updateRoute(route);
        if (flag >=1){
            return "redirect:/admin/route/page";
        }else {

            return "error";
        }
    }


    //封装图片文件处理方法
    private void performRImage(Route route,
                               @RequestParam("rimageFile") MultipartFile rImageFile,
                               HttpServletRequest request) throws IOException {

        //项目部署目录+img/product/rImage/
        //String savePath = request.getServletContext().getRealPath("img/product/rImage/");
        String savePath = "C:\\Users\\srq\\IdeaProjects\\travel\\src\\main\\resources\\static\\img\\product\\rImage";

        //处理随机文件名
        String fileName = UUID.randomUUID()
                //处理随机生成的UID
                .toString().replaceAll("-","")+"."+
                //获取文件后缀
                FilenameUtils.getExtension(rImageFile.getOriginalFilename());


        File savePathDir = new File(savePath);
        if (!savePathDir.exists()){
            //上传目录，如果不存在则创建
            savePathDir.mkdir();
        }

        //保存文件
        rImageFile.transferTo(new File(savePathDir,fileName));

        //设置路线的rImag属性的文件相对路径
        route.setRImage("img/product/rImage/"+fileName);

    }

    //删除操作
    @RequestMapping("delete/{rid}")
    public int deleteRoute(@PathVariable("rid") Integer rid){

        return routeService.deleteRoute(rid);
    }



}
